//
//  CourseListController.m
//  MetenEnglish
//
//  Created by rj-mayong on 14/11/28.
//  Copyright (c) 2014年 Shenzhen Securities Information Co., Ltd. All rights reserved.
//

#import "CourseListController.h"
#import "CourseCell.h"
#import "CourseModel.h"
#import "NetWork.h"

@interface CourseListController ()

@end

@implementation CourseListController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _courseList = [[NSMutableArray alloc] initWithCapacity:20];
    }
    return self;
}

- (void)dealloc
{
    [[HttpManager share] setReserveDelegate:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"订课";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
#if RESERVEALL == 1
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"一键订课"
                                                                style:UIBarButtonItemStyleDone
                                                               target:self
                                                               action:@selector(reserveAllCourses)];
    self.navigationItem.rightBarButtonItem = barItem;
#endif
    
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refreshCourseList:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;
}

- (void)showCoursList:(NSArray *)courseList {
    // clear the dirty data
    if (_courseList.count != 0) {
        [_courseList removeAllObjects];
    }
    [_courseList addObjectsFromArray:courseList];
    
    // stop refreshing
    if (self.refreshControl.refreshing) {
        [self.refreshControl endRefreshing];
    }
    
    [[HttpManager share] setReserveDelegate:self];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshCourseList:(id)sender {
    NSString *level = [[NSUserDefaults standardUserDefaults] objectForKey:LEVEL_KEY];
    [[HttpManager share] courseList:44 productLevelId:[level integerValue]];
}

- (void)showAlertView:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    if (_courseList.count == 0) {
        return 0;
    }
    return _courseList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cellId";
    CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (nil == cell) {
        cell = [[CourseCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:cellId
                                        cellType:CELL_COURSELIST];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.delegate = self;
    }
    
    if (_courseList.count != 0) {
        [cell setCellContent:[_courseList objectAtIndex:indexPath.row]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.0f;
}


#pragma mark - CourseCellDelegate
- (void)clickedCourseButton:(CourseModel *)courseModel {
    switch ([courseModel getCourseStatus]) {
        case COURSE_RESERVE: {
            [SVProgressHUD showWithStatus:@"正在订课"];
            [[HttpManager share] reserveCourse:[courseModel getCourseId]
                               requestUserInfo:courseModel];
        }
            break;
        case COURSE_STANDBY:
            [SVProgressHUD showWithStatus:@"正在排队"];
            [[HttpManager share] standByCourse:courseModel];
            break;
        case COURSE_CANCEL_QUEUE:
            [SVProgressHUD showWithStatus:@"正在取消排队"];
            [[HttpManager share] cancelStandByCourse:courseModel];
            break;
        default:
            break;
    }
}

- (void)reserveAllCourses {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd"];
    NSString *date = [formatter stringFromDate:[NSDate date]];
    
    for (CourseModel *model in _courseList) {
        NSString *courseDate = model.time;
        courseDate = [model.time substringToIndex:5];
        //如果是当天的课,或者不是主修课,就不订课
        if ([courseDate isEqualToString:date] ||
            model.courseCategory != COURSE_MAJOR) {
            continue;
        }
        
        if ([model getCourseStatus] == COURSE_RESERVE) {
            [[HttpManager share] reserveCourse:[model getCourseId]
                               requestUserInfo:model];
        }
    }
}

#pragma mark - ReserveCourseDelegate
- (void)reserveCourseSuccess:(CourseModel *)model reserveCourseResult:(id)result{
    [SVProgressHUD dismiss];
    BOOL isSuccess = [result boolValue];
    if (isSuccess) {
        NSInteger index = [_courseList indexOfObject:model];
        model.status = @"已订";
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]
                              withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
        DDLogInfo(@"订课成功 %@",model.name);
    }else {
        
    }
    
}

- (void)standByCourseSuccess:(CourseModel *)model queueResult:(id)result {
    [SVProgressHUD dismiss];
    BOOL isSuccess = [result boolValue];
    if (isSuccess) {
        [self showAlertView:@"排队成功"];
        NSUInteger index = [_courseList indexOfObject:model];
        model.status = @"取消排队";
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
                              withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }
    else {
        [self showAlertView:@"排队失败"];
    }
}

- (void)cancelStandBySuccess:(CourseModel *)model cancelQueueResult:(id)result {
    [SVProgressHUD dismiss];
    BOOL isSuccess = [result boolValue];
    if (isSuccess) {
        [self showAlertView:@"取消排队成功"];
        NSUInteger index = [_courseList indexOfObject:model];
        model.status = @"排队";
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
                              withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }
    else {
        [self showAlertView:@"取消失败"];
    }
}

@end
